<?php
namespace submodule\base;
use Yii;
use base\YiiMobo;
use yii\data\Pagination;
use submodule\widgets\SubmoduleWidget;
/**
 * Site controller
 */
class BaseSubmoduleController extends \backend\base\BaseBackendController
{

   
   public $layout = false;
   
   public $submodel;
   
    public function null_OperTips($array = []){
        $param = $array ? $array : ['backurl'=> '', 'error'=> true, 'title'=> '数据不存在', 'timeout'=> 3000];
        $this->OperTips($param);
    }
	
	

	/**
	 * 生成扩展类
     * 
	 */
	public function createSubmoduleExtend($end = 'Submodule', $tablename, $function){
		$tablename = rtrim(ltrim($tablename, '{{%'), '}}');
		$parentClassname = $tablename.'Extend';
		$classname = $tablename.'Editable';
		$classPath = Yii::getAlias('@'.strtolower($end))."/extend/$tablename/";
		
		$contents = file_get_contents(Yii::getAlias('@submodule').'/extend/_template/_class.php');
		$function_str = ''.PHP_EOL;
		foreach($function as $k=>$v){
			if ($v) foreach($v as $kk=>$vv){
				if (!is_numeric($kk) && $vv){
					$function_str .= '    public function '.$k.ucfirst($kk).'($fieldid, $field, $data = NULL){'.PHP_EOL;
					$function_str .= '        $value = self::getData($fieldid, $field, $data);'.PHP_EOL;
					
					foreach(explode(PHP_EOL, $vv) as $val){
						$function_str .= '        '.$val.PHP_EOL;
					}
					$function_str .= '        return $value;'.PHP_EOL;
					$function_str .= '    }'.PHP_EOL.PHP_EOL;
				}
			}
			
		}
		$namespace = str_replace('/', '\\', strtolower($end)."/extend/$tablename");
		
		$function_str = str_replace(['{{%parentClassname}}', '{{%field}}', '{{%function}}', '{{%namespace}}'], [$parentClassname, $tablename, $function_str, $namespace], $contents);
		$sFile = $classPath.$parentClassname.'.php';
		$oldmask = umask(0);
		if (!file_exists($classPath)){
			if(!mkdir($classPath, 0755, true)){
				umask($oldmask);
				$this->OperTips(['backurl'=> '', 'error'=> true, 'title'=> '创建目录失败', 'timeout'=> 3000]);
			}
		}
		$handle = fopen($sFile,'wb');
		fwrite($handle, $function_str);
		fclose($handle);
		
		$sFile = $classPath.$classname.'.php';
		if(!is_file($sFile)){
			$contents = file_get_contents(Yii::getAlias('@submodule').'/extend/_template/_classEditable.php');
			$function_str = str_replace(['{{%parentClassname}}', '{{%classname}}', '{{%field}}', '{{%function}}', '{{%namespace}}'], [$parentClassname, $classname, $tablename, $function_str, $namespace], $contents);
			$handle = fopen($sFile,'wb');
			fwrite($handle, $function_str);
			fclose($handle);
		}
    }
	/**
	 * 加载扩展类
     * 
	 */
	public function loadSubmoduleExtend($end = 'Submodule', $tablename, $models, $data, $modelid, $action){
		$tablename = rtrim(ltrim($tablename, '{{%'), '}}');
	    $class = $tablename.'Editable';
		$namespace = str_replace('/', '\\', strtolower($end)."/extend/$tablename/{$class}");
		
		//exit($sFile);
		//require($sFile);
		return new $namespace($models, $data, $modelid, $action);
    }
	
	public function loadSubmoduleValue($models, $setting, $rows, $function, $action){
		$field = $setting['field'];
		$fieldid = $setting['fieldid'];
		$view = "@submodule/models_views/{$models['models']['tablename']}/$field/index";
		$viewfunction = $field.$action;
		
		if (method_exists($function, $viewfunction)){
			$val = $function->$viewfunction($fieldid, $field, $rows);
		}else{
			$val = $rows[$field];
		}
		return $val;
	}

	public function submodelSaveCallback($id, $data){
		return $data;
		
	}
	/**
	 * 分析表单提交数据
     * 
	 */
	public function submodelSaveForm($id = '', $callback = false){
		
		$tableName = $this->submodel->models['models']['tablename'];
		$save = $this->loadSubmoduleExtend('Backend', $tableName, $this->submodel->models, $_POST['Models'], $this->submodel->modelid, $this->action->id);
		$data = [];
		$data_data = [];
		$fields = [];
		foreach($this->submodel->fields as $k=>$v){
			$fields[] = $v['field'];
			if ($v['enabled'] && $v['field'] != $this->submodel->primarykey){
				$defaultvalue = isset($v['setting']['defaultvalue']) ? $v['setting']['defaultvalue'] : (in_array($v['fieldtype'], ['int', 'tinyint', 'smallint', 'mediumint', 'integer']) ? 0 : '');
				if (!$v['allowinput']){
                    $value = $defaultvalue;
				}else{
				    $value = isset($_POST['Models'][$v['field']]) ? $_POST['Models'][$v['field']] : $defaultvalue;
			    }
				if (in_array($v['formtype'],  ['checkbox'])){
					$value = ltrim(join(',', $value), ',');
				}else if (in_array($v['field'],  ['addtime', 'updatetime'])){
					$value = time();
					if ($id && $v['field'] == 'addtime') $value = false;
				}else if(is_array($value)){
					$value = json_encode($value, JSON_UNESCAPED_UNICODE);
				}
				

		        //$namespace = "submodule\widgets\datetime\\".$v['formtype'].'Editable';

		        //return new $namespace($this->submodel->models, $_POST['Models'], $this->submodel->modelid, $this->action->id);
				
				
				
				
			    
				if (method_exists($save, $v['field'].'Save')){
					$savefunction = $v['field'].'Save';
					$value = $save->$savefunction($v['fieldid'], $v['field']);
				}
				
				
                if($value !== false) $data[$v['primarytable']][$v['field']] = $value;
				
			}
		}
		//$data['modelid'] = $this->submodel->modelid; 
		
		
		
		
		$data = $this->submodelSaveCallback($id, $data);
		$this->submodelSave($id, $data);
		
	}
	/**
	 * 保存表单提交数据到数据库
     * 
	 */
	public function submodelSave($id, $data){
		$connection = Yii::$app->db;
        $connection->open();
		//update
		if ($id){
			$insertid = $id;
			$connection->createCommand()->update($this->submodel->tablename, $data[1], $this->submodel->primarykey.' = '.$id)->execute();
			if($this->submodel->data_tablename){
				$connection->createCommand()->update($this->submodel->data_tablename, $data[0], $this->submodel->primarykey.' = '.$id)->execute();
			}
		//insert
		}else{
		    $connection->createCommand()->insert($this->submodel->tablename, $data[1])->execute();
			$insertid = $data[0][$this->submodel->primarykey] = $connection->getLastInsertID();
			if($this->submodel->data_tablename && isset($data[0])){
				$connection->createCommand()->insert($this->submodel->data_tablename, $data[0])->execute();
			}
		}


		try{
			if($this->submodel->models['models']['type'] == 'category'){
				$depth = $this->CategoryDepth($this->submodel->modelid, $insertid);
			    $connection->createCommand()->update($this->submodel->tablename, ['depth'=> join(',', $depth)], 'id = '.$insertid)->execute();
			    $children = $this->CategoryChildren($this->submodel->modelid, $insertid);
			    $connection->createCommand()->update($this->submodel->tablename, ['children'=> $children], 'id = '.$insertid)->execute();
				$this->updateCategoryCache();
			}
			$data['backurl'] = $this->createUrl([$this->submodel->controllerUrl['index'], 'modelid'=>$this->submodel->modelid]);
			if(Yii::$app->request->getIsAjax()){
				
				$this->echojson($data);
			}else{
			    $this->OperTips($data['backurl']);
			}
		}catch (Exception $e){
			var_dump($e);
		}
		
	}
	
	public function formWidgets($path, $action, $attributes=[]){
		$widgets = [];
		$function = $this->loadSubmoduleExtend($path, $this->submodel->models['models']['tablename'], $this->submodel->models, $attributes, $this->submodel->modelid, $this->action->id);
		$formname = 'Models';
		if($action == 'search'){
			$fields = $this->searchFields();
			$formname = 'search';
		}else if($action == 'form'){
			$fields = $this->formFields();
		}
		foreach($fields as $v){
			$widgets[$v['fieldid']]['fields'] = ['field'=> $v['field'], 'name'=> $v['name'], 'required'=> $v['required']];
             $widgets[$v['fieldid']]['widgets'] = SubmoduleWidget::widget(['viewPath'=>$v['formtype'], 'options' => [
				'primarykey'=> $this->submodel->primarykey,
				'value'=> '',
				'fields'=> $v,
				'id'=> $v['field'],
				'name'=> $formname.'['.$v['field'].']',
				'attributes'=> $attributes,
                'setting'=> $v['setting'],
				'param'=> $v['param']
	
			], 'function'=>$function]);
		}
        return $widgets;               
	}
	/**
	 * HEAD加载的组件JS及CSS
     * 
	 */
	public function getSubmodelheaderPlugins(){
		$plugins = array();
		foreach($this->submodel->fields as $v){
			if (in_array($v['formtype'],  ['image', 'images'])){
				$plugins[] = 'webuploader';
			}else if ($v['formtype'] == 'ueditor'){
				$plugins[] = 'ueditor';
			}else if ($v['formtype'] == 'datetime'){
				$plugins[] = 'datetimepicker';
			}
		}
		return $plugins;
	}

	public function getSql($type = 'index'){

		return ['sql'=> $sql, 'orderby'=> $orderby];
		
	}
	/**
	 * 检查数据库表是否存在
     * 
	 */
	public function checkTableName($tablename){
		if ($tablename){
		    $tablename = Yii::$app->db->tablePrefix.rtrim(ltrim($tablename, '{{%'), '}}');
		    $sql="SHOW TABLES LIKE '{$tablename}'";
		    return Yii::$app->db->createCommand($sql)->queryOne();
		}else{
			return false;
		}
	}
	/**
	 * 允许后台录入的表单
	 * 
	 */
	public function formFields(){
		$data = [];
		foreach($this->submodel->fields as $v){
			if (!$v['allowinput'] || !$v['enabled'] || $v['formtype'] == 'primarykey') continue;
			if (!in_array($v['field'], $this->submodel->default_field)){
				$data[] = $v;
			}
		}
		return $data;
		
	}
	/**
	* 返回可搜索的字段
	*/
    public function searchFields(){
	    $fields = [];
		foreach($this->submodel->fields as $v){
			if (isset($v['setting']['search']) && $v['setting']['search'] == 1){
				$fields[] = $v;
			}
		}
		return $fields;
	}
}
